<?php

namespace App\Services\SaleOrder;


use App\Models\Order\Salesordersub;
use App\Models\Purchase\PurchaseOrderSub;
use App\Models\Saleprice\Saleprice as ModelSaleprice;
use App\Models\Systemparam\Systemparam as ModelSystemparam;

class SaleOrder
{


    /**
     *
     *  计算计和业绩
     * @param $params
     * @param $mangerinfo
     * @param $isTrans
     * @return array|\Illuminate\Http\JsonResponse|string[]
     * @throws \Exception
     */
    public function getaccrualperformance($params, $mangerinfo, $isTrans = true)
    {
        $cpid = $mangerinfo['cpid'];
        $node = $params['node'] ?? 'sale_order';
        $sales_sub_id = $params['sales_sub_id'] ?? 0; //当前子订单id, 销售订单/发货 都存在
        $id = $params['id'] ?? 0; //当前子订单id, 销售订单/发货 都存在
        $is_sys_purchase = $params['is_sys_purchase'] ?? 0; // 1常规 2自采
        $unit_price = $params['unit_price'] ?? 0;
        $otherfee_total = $params['salefee'] ?? 0;
        $total_weight = $params['total_weight'] ?? 0;
        $guiding_price = $params['guiding_price'] ?? 0;//指导价 考虑后端获取(销售指导价/采购指导价)
        if ((int)$is_sys_purchase==0) {
            return ['accrual' => 0, 'performance' => 0];
        }
        /****
         *
         * 金额 转化为 分
         * 重量统一转化为 g
         *
         */
        if ($isTrans === true) {
            $unit_price = $this->amountTransformIntoCent($unit_price);
            $guiding_price = $this->amountTransformIntoCent($guiding_price);
            $otherfee_total = $this->amountTransformIntoCent($otherfee_total);
            $total_weight = $this->weightTransformIntoG($total_weight);
        }


        /**
         * 差额（销售发货单创建后，可在统审端-发货单-子订单 维护差额，默认0），参与业绩计算。
         *
         *
         */
        $diff = 0;
        $accrual = 0;
        $performance = 0;
        if ($node == 'sales_order' && !empty($id)) {
            $diff = Salesordersub::query()->where('id', $id)->value('diff');
        }
        if ((int)$is_sys_purchase == 1) {
            $accrual = $this->accrual_in_normal_purchase($cpid, $unit_price, $otherfee_total, $guiding_price);
            $performance = $this->performance($accrual, $total_weight, $diff);
        }
        /***
         *
         * 自采订单,取采购价格，计算 计提/业绩
         * 采购订单，未生成前可修改，已生成采购价不可修改（常规采购流程，采购价格跟随合同，没有时手动输入）
         *
         * 自采订单绑定合同后，价格不可修改
         *
         */
        if ((int)$is_sys_purchase == 2) {
            /***
             * 获取自采订单 指导价
             * 子订单id为0，无法获取采购价格，业绩/计提 不计算直接返回0
             *
             * sales_sub_id 当前子订单id
             *
             * 已销定采修改后，有采购基价，加价。可参与计算 2025.05.22
             *
             */

            if ($sales_sub_id) {
                $purchaseOrderSub = PurchaseOrderSub::query()->where('sale_sub_id', $sales_sub_id)->first();
                if (!empty($purchaseOrderSub) && $purchaseOrderSub['price'] > 0) {
                    $guiding_price = $this->getSystemPurchaseGuidingPrice($sales_sub_id);
                    $accrual = $this->accrual_in_system_purchase($cpid, $unit_price, $otherfee_total, $guiding_price);
                    $performance = $this->performance($accrual, $total_weight, $diff);
                }
            }
        }

        if ($isTrans === true) {
            $res = [
                'accrual' => $this->amountTransformIntoYuan($accrual),
                'performance' => $this->amountTransformIntoYuan($performance),
            ];
        } else {
            $res = [
                'accrual' => $accrual,
                'performance' => $performance
            ];
        }

        return $res;
    }


    /**
     *
     * 金额转分
     * @param $amount
     * @return mixed|string
     * @throws \Exception
     */
    public function amountTransformIntoCent($amount = 0)
    {
        return mathfuncmoney('mul', $amount, 100, 2);
    }

    /**
     * 分转园
     * @param $amount
     * @return mixed|string
     * @throws \Exception
     */
    public function amountTransformIntoYuan($amount = 0)
    {
        return mathfuncmoney('div', $amount, 100, 2);
    }


    /**
     * 吨转克
     * @param $amount
     * @return mixed|string
     * @throws \Exception
     */
    public function weightTransformIntoG($weight = 0)
    {
        return mathfuncmoney('mul', $weight, 10000, 2);
    }


    /**
     * 克转吨
     * @param $amount
     * @return mixed|string
     * @throws \Exception
     */
    public function weightTransformIntoTon($weight = 0)
    {
        return mathfuncmoney('div', $weight, 10000, 2);
    }



    public function accrual_in_normal_purchase($cpid=0,$unit_price =0,$otherfee_total=0,$guiding_price=0){
        //库存产品计提加成
        $companycosts = 0;
        $costs = ModelSystemparam::where(['cpid' => $cpid, 'type' => 'company_costs'])->value('value') ?? 0;
        if ($costs) {
            $companycosts = mathfuncmoney('mul',$costs,100,2);
        }

        //2025-09-18  销售单价=销售单价+费用单价总和  所以计算不扣除费用单价  bugid:19661
//        $res_money = mathfunc('sub',$unit_price,$otherfee_total,2);
        $res_money = mathfunc('sub',$unit_price,$guiding_price,2);
        $res_money = mathfunc('add',$res_money,$companycosts,2);


        return $res_money;
    }


    /***
     *
     * 业绩计算公式
     *  业绩=计提*吨数+差额。 差额：统审端-销售发货单（子订单），填写 采购订单差额
     *  $accrual $diff 分
     *  $total_weight g
     *
     */
    public function performance($accrual=0,$total_weight=0,$diff=0){
        $performance = mathfunc('mul',$accrual,$total_weight,2);
        $performance = mathfunc('div',$performance,10000,2);

        $performance = mathfunc('add',$performance,$diff,2);
        return $performance;
    }


    /***
     *  自采订单，计提 业绩
     *  销售业务计提=销售单价-销售费用单价总和(其他费用之和)-计提底价，(计提底价=自采采购价+自采计提扣减成本(在系统管理原
     *  管理员端计提管理下边的自采计提扣减成本) 自采采购价=采购基价+加价
     *  自采采购价 = $guiding_price
     *
     */
    public function accrual_in_system_purchase($cpid=0,$unit_price=0,$otherfee_total=0,$guiding_price=0){
        //自采计提扣减成本
        $sys_purchase_company_costs = 0;
        $costs = ModelSystemparam::where(['cpid' => $cpid, 'type' => 'sys_purchase_company_costs'])->value('value') ?? 0;
        if ($costs) {
            $sys_purchase_company_costs = mathfuncmoney('mul',$costs,100,2);

        }
        //2025-09-18  销售单价=销售单价+费用单价总和  所以计算不扣除费用单价  bugid:19661
//        $res_money = mathfunc('sub',$unit_price,$otherfee_total,2);
        $res_money = mathfunc('sub',$unit_price,$guiding_price,2);
        $res_money = mathfunc('sub',$res_money,$sys_purchase_company_costs,2);

        return $res_money;
    }


    /***
     * 获取 自采订单，指导价
     * 通过销售子订单 直接查询 采购子订单
     *
     *
     */
    public function getSystemPurchaseGuidingPrice($sales_sub_id = 0){
        $PurchaseOrderSub = PurchaseOrderSub::where('sale_sub_id',$sales_sub_id)->first();
        if(!$PurchaseOrderSub){
            return 0;
        }
        $guiding_price = mathfunc('add',$PurchaseOrderSub['base_price'],$PurchaseOrderSub['add_price']);
        return $guiding_price;
    }



    /**
     * 获取钢材加价
     */
    public function getsteelprice($price_data, $base_price, $item)
    {
        //仓库
        if (!empty($price_data['warehouse_name'][$item['warehouse_name']])) {
            $warehouse_price = $price_data['warehouse_name'][$item['warehouse_name']]['amount'];
            $op = $price_data['warehouse_name'][$item['warehouse_name']]['op'];
            if ($op == 1) {
                $base_price = $base_price + $warehouse_price;
            } else {
                $base_price = $base_price - $warehouse_price;
            }
        }
        //钢厂
        if (!empty($price_data['steel_factory_name'][$item['steel_factory_name']])) {
            $steel_factory_price = $price_data['steel_factory_name'][$item['steel_factory_name']]['amount'];
            $op = $price_data['steel_factory_name'][$item['steel_factory_name']]['op'];
            if ($op == 1) {
                $base_price = $base_price + $steel_factory_price;
            } else {
                $base_price = $base_price - $steel_factory_price;
            }
        }
        //品种
        if (!empty($price_data['breed_name'][$item['breed_name']])) {
            $breed_price = $price_data['breed_name'][$item['breed_name']]['amount'];
            $op = $price_data['breed_name'][$item['breed_name']]['op'];
            if ($op == 1) {
                $base_price = $base_price + $breed_price;
            } else {
                $base_price = $base_price - $breed_price;
            }
        }
        //材质
        if (!empty($price_data['archive_material'][$item['archive_material']])) {
            $archive_material_price = $price_data['archive_material'][$item['archive_material']]['amount'];
            $op = $price_data['archive_material'][$item['archive_material']]['op'];
            if ($op == 1) {
                $base_price = $base_price + $archive_material_price;
            } else {
                $base_price = $base_price - $archive_material_price;
            }
        }

        if ($item['archive_type'] != 2) {
            $spec_arr = explode('*', $item['archive_spec']);

            if (!empty($spec_arr[0])) {
                if (!empty($price_data['specs_1'][$spec_arr[0]])) {
                    $specs_1_price = $price_data['specs_1'][$spec_arr[0]]['amount'];
                    $op = $price_data['specs_1'][$spec_arr[0]]['op'];
                    if ($op == 1) {
                        $base_price = $base_price + $specs_1_price;
                    } else {
                        $base_price = $base_price - $specs_1_price;
                    }
                }
            }

            if (!empty($spec_arr[1])) {
                if (!empty($price_data['specs_2'][$spec_arr[1]])) {
                    $specs_2_price = $price_data['specs_2'][$spec_arr[1]]['amount'];
                    $op = $price_data['specs_2'][$spec_arr[1]]['op'];
                    if ($op == 1) {
                        $base_price = $base_price + $specs_2_price;
                    } else {
                        $base_price = $base_price - $specs_2_price;
                    }
                }
            }

            if (!empty($spec_arr[2])) {
                if ($item['archive_type'] == 3) {
                    if (!empty($price_data['specs_3'][$spec_arr[2]])) {
                        $specs_3_price = $price_data['specs_3'][$spec_arr[2]]['amount'];
                        $op = $price_data['specs_3'][$spec_arr[2]]['op'];
                        if ($op == 1) {
                            $base_price = $base_price + $specs_3_price;
                        } else {
                            $base_price = $base_price - $specs_3_price;
                        }
                    }
                }
            }
        }

        //码单
        switch ($item['archive_type']) {
            case 1:
                $archive_type = '理计';
                break;
            case 2:
                $archive_type = '过磅';
                break;
            case 3:
                $archive_type = '定尺';
                break;
            case 4:
                $archive_type = '虚拟';
                break;
        }
        if (isset($price_data['archive_type'][$archive_type])) {
            $archive_type_price = $price_data['archive_type'][$archive_type]['amount'];
            $op = $price_data['archive_type'][$archive_type]['op'];
            if ($op == 1) {
                $base_price = $base_price + $archive_type_price;
            } else {
                $base_price = $base_price - $archive_type_price;
            }
        }
        return $base_price;
    }


    /**
     * 获取销售基价、加价
     */
    public function getsaleprice($mangerinfo)
    {
        $cpid = $mangerinfo['cpid'] ?? 0;
        $list = ModelSaleprice::query()->where(['cpid' => $cpid, 'is_del' => config('constants.is_del.no')])->get();
        if (!empty($list)) {
            $list = $list->toArray();
            $data = [];
            foreach ($list as $item) {
                $data[$item['type']][$item['name']]['name'] = $item['name'];
                $data[$item['type']][$item['name']]['op'] = $item['op'];
                $data[$item['type']][$item['name']]['amount'] = $item['amount'];
            }
            return $data;
        } else {
            return [];
        }
    }

}
